package com.iseastar.guojiang.register;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.app.ocr.ui.camera.CameraNativeHelper;
import com.app.ocr.ui.camera.CameraView;
import com.app.ocr.ui.camera.OCRCameraActivity;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.iseastar.BaseActivity2;
import com.iseastar.dianxiaosan.model.Const;
import com.iseastar.guojiang.BeeApplication;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.app.CourierCameraActivity;
import com.iseastar.guojiang.consts.AppConfig;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.IDCardInfoBean;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.UserBean;
import com.shouhuobao.station.R;
import com.shouhuobao.station.wxapi.Constants;

import java.io.File;

import droid.frame.ui.utils.Utils;
import droid.frame.utils.android.Log;
import droid.frame.utils.http.BitmapUtils;
import droid.frame.utils.lang.FileUtils;
import droid.frame.utils.lang.Str;

/**
 * Created by joker on 2018/4/26.
 * 完善火箭侠身份
 */
public class CourierPerfectInformationActivity extends BaseActivity2 implements View.OnClickListener {

    private static final int REQUEST_CODE_PICK_IMAGE_FRONT = 201;
    private static final int REQUEST_CODE_PICK_IMAGE_BACK = 202;
    private static final int REQUEST_CODE_CAMERA = 102;
    private boolean hasGotToken = false;

    private ImageView mIDCardIV;//身份证
    private ImageView mHandIV;//手持身份证
    private Button mSubmitBT;
    private IDCardInfoBean idCardInfoBean = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        idCardInfoBean = AppCache.getIdCardInfoBean();
        if (idCardInfoBean == null) {
            idCardInfoBean = new IDCardInfoBean();
            AppCache.setIdCardInfoBean(idCardInfoBean);
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_register_perfectinformation);
        super.findViewById();
        getAppTitle().setCommonTitle("完善资料");
        mIDCardIV = (ImageView) findViewById(R.id.courier_font_iv);
        mHandIV = (ImageView) findViewById(R.id.courier_hand_iv);
        mSubmitBT = (Button) findViewById(R.id.submit_bt);
        mIDCardIV.setOnClickListener(this);
        mHandIV.setOnClickListener(this);
        setButtonEnableStyle(mSubmitBT, false);
        // 请选择您的初始化方式
        initAccessTokenWithAkSk();
    }

    private boolean checkTokenStatus() {
        if (!hasGotToken) {
            showToast("token获取失败");
        }
        return hasGotToken;
    }

    private void initAccessTokenWithAkSk() {
        OCR.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                hasGotToken = true;
                //  初始化本地质量控制模型,释放代码在onDestory中
                //  调用身份证扫描必须加上 intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL, true); 关闭自动初始化和释放本地模型
                CameraNativeHelper.init(getContext(), OCR.getInstance().getLicense(),
                        new CameraNativeHelper.CameraNativeInitCallback() {
                            @Override
                            public void onError(int errorCode, Throwable e) {
                                String msg;
                                switch (errorCode) {
                                    case CameraView.NATIVE_SOLOAD_FAIL:
                                        msg = "加载so失败，请确保apk中存在ui部分的so";
                                        break;
                                    case CameraView.NATIVE_AUTH_FAIL:
                                        msg = "授权本地质量控制token获取失败";
                                        break;
                                    case CameraView.NATIVE_INIT_FAIL:
                                        msg = "本地质量控制";
                                        break;
                                    default:
                                        msg = String.valueOf(errorCode);
                                }
                                Log.d("11111", "本地质量控制初始化错误，错误原因： " + msg);
                            }
                        });
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                showToast("文字识别验证失败");
            }
        }, BeeApplication.getContext(), Constants.OCR_APP_KEY, Constants.OCR_APP_SECRET);
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            //拍照身份证照片并识别
            case R.id.courier_font_iv:
                intent = new Intent(getContext(), OCRCameraActivity.class);
                intent.putExtra(Const.KEY_OUTPUT_FILE_PATH, FileUtils.getSaveFile(getContext()).getAbsolutePath());
                intent.putExtra(Const.KEY_NATIVE_ENABLE,
                        true);
                // KEY_NATIVE_MANUAL设置了之后CameraActivity中不再自动初始化和释放模型
                // 请手动使用CameraNativeHelper初始化和释放模型
                // 推荐这样做，可以避免一些activity切换导致的不必要的异常
                intent.putExtra(Const.KEY_NATIVE_MANUAL,
                        true);
                intent.putExtra(Const.KEY_CONTENT_TYPE, Const.CONTENT_TYPE_ID_CARD_FRONT);//
                startActivityForResult(intent, REQUEST_CODE_CAMERA);
                break;
            //拍照手持身份证照片
            case R.id.courier_hand_iv:
                intent = new Intent(getContext(), CourierCameraActivity.class);
                startActivityForResult(intent, 103);
                break;
            //点击提交审核
            case R.id.submit_bt:
                if (idCardInfoBean == null || isEmpty(idCardInfoBean.getLocalIDCardImagePath()) || isEmpty(idCardInfoBean.getLocalInHandCardImagePath())) {
                    return;
                }
                showLoadingDialog("正在上传图片");
                AppHttp.getInstance().postFils(idCardInfoBean.getLocalIDCardImagePath(), idCardInfoBean.getLocalInHandCardImagePath());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && 103 == requestCode) {//选取要识别的图片
            String capturePath = data.getStringExtra("file");
            if (!Str.isEmpty(capturePath)) {
                handlerLoadImage(capturePath);
            }
        } else if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String contentType = data.getStringExtra(Const.KEY_CONTENT_TYPE);
                String filePath = FileUtils.getSaveFile(getApplicationContext()).getAbsolutePath();
                String imagePath = data.getStringExtra("filePath");
                if (!TextUtils.isEmpty(contentType)) {
                    if (Const.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath, imagePath);
                    } else if (Const.CONTENT_TYPE_ID_CARD_BACK.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath, imagePath);
                    }
                }
            }
        }
    }

    private void recIDCard(final String idCardSide, final String filePath, final String imagePath) {
        IDCardParams param = new IDCardParams();
        param.setImageFile(new File(filePath));
        // 设置身份证正反面
        param.setIdCardSide(idCardSide);
        // 设置方向检测
        param.setDetectDirection(true);
        // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
        param.setImageQuality(20);

        OCR.getInstance().recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult result) {
                if (result != null) {
                    if (IDCardParams.ID_CARD_SIDE_FRONT.equals(idCardSide)) {
                        if (isNotEmpty(imagePath)) {
                            setIDCardBitmap(result, imagePath);
                        } else {
                            String IDCardPath = AppConfig.getCaptureDir() + "/" + System.currentTimeMillis();
                            if (FileUtils.copy(filePath, IDCardPath)) {
                                setIDCardBitmap(result, IDCardPath);
                            }
                        }
                    }
                }
                Log.d("11111", result.toString());
            }

            @Override
            public void onError(OCRError error) {
                Log.e("11111", "文字识别异常", error);
            }
        });
    }

    /**
     * 设置身份证扫描图片
     *
     * @param result
     * @param path
     */
    private void setIDCardBitmap(IDCardResult result, String path) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        if (bitmap != null && isNotEmpty(result.getName())
                && isNotEmpty(result.getGender()) && isNotEmpty(result.getEthnic())
                && isNotEmpty(result.getIdNumber()) && isNotEmpty(result.getAddress())) {
            mIDCardIV.setImageBitmap(bitmap);
            idCardInfoBean.setLocalIDCardImagePath(path);
            idCardInfoBean.setName(result.getName().toString());
            idCardInfoBean.setGender(result.getGender().toString());
            idCardInfoBean.setEthnic(result.getEthnic().toString());
            idCardInfoBean.setIdNumber(result.getIdNumber().toString());
            idCardInfoBean.setAddress(result.getAddress().toString());
            if (isNotEmpty(idCardInfoBean.getLocalInHandCardImagePath())) {
                setButtonEnableStyle(mSubmitBT, true);
            } else {
                setButtonEnableStyle(mSubmitBT, false);
            }
        } else {
            showToast("识别失败");
        }
    }

    private void handlerLoadImage(String picPath) {
        int width = getResources().getDisplayMetrics().widthPixels;
        int bitmapWidth = 0;
        if (width != 0) {
            bitmapWidth = (width - Utils.dpToPx(42, getResources())) / 2;
        } else {
            bitmapWidth = Utils.dpToPx(155, getResources());
        }
        Bitmap imageThumbnail = BitmapUtils.getImageThumbnail(picPath, bitmapWidth, Utils.dpToPx(99.5f, getResources()));
        if (imageThumbnail != null) {
            idCardInfoBean.setLocalInHandCardImagePath(picPath);
            mHandIV.setImageBitmap(imageThumbnail);
            if (isNotEmpty(idCardInfoBean.getLocalIDCardImagePath())) {
                setButtonEnableStyle(mSubmitBT, true);
            } else {
                setButtonEnableStyle(mSubmitBT, false);
            }
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            //上传头像返回图片路径
            case MsgID.upload_image:
                ReqResult<String> reqResult = JSON.parser(msg.obj, String.class);
                if (checkLoginStatus(reqResult)) {
                    if (reqResult.getResult() == null || idCardInfoBean == null) {
                        cancelLoadingDialog();
                        showToast("图片上传失败");
                        return true;
                    }
                    String path = reqResult.getResult().replace("\\", "").replace("[", "").replace("]", "").replace("\"", "");
                    String[] resultImagePath = path.split(",");
                    if (resultImagePath == null || resultImagePath.length < 1) {
                        cancelLoadingDialog();
                        showToast("图片上传失败");
                        return true;
                    }
                    idCardInfoBean.setiDCardImagePath(resultImagePath[0]);
                    idCardInfoBean.setInHandCardImagePath(resultImagePath[1]);
                    showLoadingDialog("正在上传资料");
                    AppHttp.getInstance().courierSubmitIdCardInfo(idCardInfoBean);
                } else {
                    cancelLoadingDialog();
                    showToast(reqResult.getMessage());
                }
                return false;
            case MsgID.courier_submit_idcard_info:
                cancelLoadingDialog();
                ReqResult<?> result = JSON.parser(msg.obj);
                if (checkLoginStatus(result)) {
                    UserBean userBean = AppCache.getUser();
                    userBean.setState(Const.CourierRegisterStatus.AuditStatus);
                    UserBean.CourierAudit courierAudit = userBean.getCourierAudit();
                    if (courierAudit == null) {
                        courierAudit = new UserBean.CourierAudit();
                    }
                    courierAudit.setName(idCardInfoBean.getName());
                    courierAudit.setAuditStatus(1);
                    if ("女".equals(idCardInfoBean.getGender())) {
                        courierAudit.setSex(2);
                    } else {
                        courierAudit.setSex(1);
                    }
                    courierAudit.setNation(idCardInfoBean.getEthnic());
                    courierAudit.setIdCardFaceImg(idCardInfoBean.getiDCardImagePath());
                    courierAudit.setIdCardBackImg(idCardInfoBean.getInHandCardImagePath());
                    courierAudit.setIdCardNo(idCardInfoBean.getIdNumber());
                    courierAudit.setAddresss(idCardInfoBean.getAddress());
                    courierAudit.setPhone(userBean.getPhone());
                    userBean.setCourierAudit(courierAudit);
                    AppCache.setUser(userBean);
                    setResult(Activity.RESULT_OK);
                    finish();
                } else {
                    showToast(result.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    /**
     * 修改密码的登录按钮
     *
     * @param button
     * @param enable
     */
    public void setButtonEnableStyle(Button button, boolean enable) {
        int bottom = button.getPaddingBottom();
        int top = button.getPaddingTop();
        int right = button.getPaddingRight();
        int left = button.getPaddingLeft();
        if (enable) {
            button.setBackgroundResource(R.drawable.app_courier_press_shape);
            button.setTextColor(getResources().getColorStateList(R.color.white));
            button.setOnClickListener(this);
        } else {
            button.setBackgroundResource(R.drawable.app_courier_disable_shape);
            button.setTextColor(getResources().getColor(R.color.white));
            button.setOnClickListener(null);
        }
        button.setPadding(left, top, right, bottom);
    }

    @Override
    protected void onDestroy() {
        // 释放本地质量控制模型
        CameraNativeHelper.release();
        // 释放内存资源
        OCR.getInstance().release();
        super.onDestroy();
    }
}
